package cn.doitedu.data_export;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;

public class EsQuery {
    public static void main(String[] args) throws IOException {

        // es的请求客户端
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("doitedu", 9200, "http")));
        // 用于查询参数封装的对象
        SearchRequest request = new SearchRequest("doit34");

        /**
         * 单一条件查询
         */
        // 定义一个 范围查询条件
        RangeQueryBuilder tag02 = QueryBuilders.rangeQuery("tag02").gt(14);

        // 将查询条件参数，封装成查询请求
        request.source(new SearchSourceBuilder().query(tag02));

        // 用客户端发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        response.getHits().forEach(ht-> System.out.println(ht.getId()));

        System.out.println("---------------分割线----------------");

        /**
         * 组合条件查询
         */
        // 定义一个 条件组装器
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        // 定义一个 范围条件
        RangeQueryBuilder tag02Query = QueryBuilders.rangeQuery("tag02").gt(14);

        // 定义一个分词匹配条件
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("tag04", "汽车");

        // 组装查询条件
        BoolQueryBuilder queryBuilder = boolQueryBuilder.must(tag02Query).must(matchQueryBuilder);

        // 将查询条件参数，封装成查询请求
        request.source(new SearchSourceBuilder().query(queryBuilder));

        // 用客户端发送请求
        SearchResponse response2 = client.search(request, RequestOptions.DEFAULT);
        response2.getHits().forEach(ht-> System.out.println(ht.getId()));


        client.close();

    }

}
